package cn.fresh.xuanyuan.module.member.service.message;

import cn.fresh.xuanyuan.framework.common.pojo.PageParam;
import cn.fresh.xuanyuan.framework.common.pojo.PageResult;
import cn.fresh.xuanyuan.module.member.dal.dataobject.message.MessageDO;
import cn.fresh.xuanyuan.module.member.dal.mysql.message.MessageMapper;
import cn.fresh.xuanyuan.module.member.dto.MessageDto;
import cn.fresh.xuanyuan.module.member.enums.MsgTypeEnum;
import cn.fresh.xuanyuan.module.member.vo.MessageCountVO;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Resource
    private MessageMapper messageMapper;

    @Override
    public MessageCountVO getUnread(Long userId) {
        Long num1 = messageMapper.getUnreadByType(userId, MsgTypeEnum.LOGISTIC_MSG.getType());
        Long num2 = messageMapper.getUnreadByType(userId, MsgTypeEnum.SYS_MSG.getType());
        Long total = num1 + num2;
        MessageCountVO countVO = new MessageCountVO();
        countVO.setLogisticsMsg(num1);
        countVO.setSysMsg(num2);
        countVO.setTotal(total);
        return countVO;
    }

    @Override
    public PageResult<MessageDto> getMsgList(Long userId, Integer msgType, PageParam pageParam) {
        PageResult<MessageDO> page = messageMapper.getMessageList(userId, msgType, pageParam);
        List<MessageDto> list = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(page.getList())) {
            for(MessageDO m : page.getList()) {
                MessageDto d = new MessageDto();
                BeanUtils.copyProperties(m,d);
                d.setMsgBody(JSON.parseObject(m.getContent()));
                list.add(d);
            }
        }
        PageResult<MessageDto> pageResult = new PageResult<>(list, page.getTotal());
        return pageResult;
    }

    @Override
    public void read(String id) {
        MessageDO updateMsg = new MessageDO();
        updateMsg.setId(id);
        updateMsg.setReadStatus(true);
        updateMsg.setReadTime(LocalDateTime.now());
        messageMapper.updateById(updateMsg);
    }
}
